package com.bwie.service.Impl;

import com.alibaba.fastjson.JSON;
import com.bwie.mapper.LogMapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.Log;
import com.bwie.pojo.User;
import com.bwie.utils.R;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.HotelMapper;
import com.bwie.pojo.Hotel;
import com.bwie.service.HotelService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements HotelService{
    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogMapper logMapper;
    @Override
    public R getHotel() {
        String token = request.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer id = body.get("id", Integer.class);
        User user = userMapper.selectById(id);
        if(ObjectUtils.isEmpty(user)){
            return R.ERROR(500,"用户未注册");
        }
        List<Hotel> hotels = hotelMapper.selectList(user.getUserPhone());
        return R.OK(hotels);
    }

    @Override
    public R updateHitel(Hotel hotel) {
        //查询酒店是否存在
        Hotel hotel1 = hotelMapper.selectById(hotel.getId());
        if(ObjectUtils.isEmpty(hotel1)){
            return R.ERROR(500,"酒店不存在");
        }
        hotelMapper.updateById(hotel1);
        Log log1 = new Log();
        log1.setLogName("酒店编辑");
        log1.setLogBody(JSON.toJSONString(hotel));
        log1.setLogTime(new Date());
        log1.setLogIp(request.getRemoteAddr());
        logMapper.insert(log1);
        return R.OK();
    }

    @Override
    public R getHotelById(Integer hotelId) {
        Hotel hotel = hotelMapper.selectById(hotelId);
        if(ObjectUtils.isEmpty(hotel)){
            return R.ERROR(500,"酒店不存在");
        }
        return R.OK(hotel);
    }
}
